<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Chapter 2 Getting Started | Data visualisation using R, for researchers who don’t use R</title>
<meta name="author" content="Emily Nordmann, Phil McAleer, Wilhelmiina Toivo, Helena Paterson, Lisa DeBruine">
<meta name="description" content="2.1 Loading packages To load the packages that have the functions we need, use the library() function. Whilst you only need to install packages once, you need to load any packages you want to use...">
<meta name="generator" content="bookdown 0.25 with bs4_book()">
<meta property="og:title" content="Chapter 2 Getting Started | Data visualisation using R, for researchers who don’t use R">
<meta property="og:type" content="book">
<meta property="og:url" content="https://psyteachr.github.io/introdataviz/getting-started.html">
<meta property="og:image" content="https://psyteachr.github.io/introdataviz/images/logos/logo.png">
<meta property="og:description" content="2.1 Loading packages To load the packages that have the functions we need, use the library() function. Whilst you only need to install packages once, you need to load any packages you want to use...">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Chapter 2 Getting Started | Data visualisation using R, for researchers who don’t use R">
<meta name="twitter:description" content="2.1 Loading packages To load the packages that have the functions we need, use the library() function. Whilst you only need to install packages once, you need to load any packages you want to use...">
<meta name="twitter:image" content="https://psyteachr.github.io/introdataviz/images/logos/logo.png">
<!-- JS --><script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.6/clipboard.min.js" integrity="sha256-inc5kl9MA1hkeYUt+EC3BhlIgyp/2jDIyBLS6k3UxPI=" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/fuse.js/6.4.6/fuse.js" integrity="sha512-zv6Ywkjyktsohkbp9bb45V6tEMoWhzFzXis+LrMehmJZZSys19Yxf1dopHx7WzIKxr5tK2dVcYmaCk2uqdjF4A==" crossorigin="anonymous"></script><script src="https://kit.fontawesome.com/6ecbd6c532.js" crossorigin="anonymous"></script><script src="libs/jquery-3.6.0/jquery-3.6.0.min.js"></script><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="libs/bootstrap-4.6.0/bootstrap.min.css" rel="stylesheet">
<script src="libs/bootstrap-4.6.0/bootstrap.bundle.min.js"></script><script src="libs/bs3compat-0.3.1/transition.js"></script><script src="libs/bs3compat-0.3.1/tabs.js"></script><script src="libs/bs3compat-0.3.1/bs3compat.js"></script><link href="libs/bs4_book-1.0.0/bs4_book.css" rel="stylesheet">
<script src="libs/bs4_book-1.0.0/bs4_book.js"></script><!-- Global site tag (gtag.js) - Google Analytics --><script async src="https://www.googletagmanager.com/gtag/js?id=G-6NP3MF25W3"></script><script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());

      gtag('config', 'G-6NP3MF25W3');
    </script><script src="https://cdnjs.cloudflare.com/ajax/libs/autocomplete.js/0.38.0/autocomplete.jquery.min.js" integrity="sha512-GU9ayf+66Xx2TmpxqJpliWbT5PiGYxpaG8rfnBEk1LL8l1KGkRShhngwdXK1UgqhAzWpZHSiYPc09/NwDQIGyg==" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/mark.min.js" integrity="sha512-5CYOlHXGh6QpOFA/TeTylKLWfB3ftPsde7AnmhuitiTX4K5SqCLBeKro6sPS8ilsz1Q4NRx3v8Ko2IBiszzdww==" crossorigin="anonymous"></script><!-- CSS --><style type="text/css">
    
    div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
  </style>
<style type="text/css">
    /* Used with Pandoc 2.11+ new --citeproc when CSL is used */
    div.csl-bib-body { }
    div.csl-entry {
      clear: both;
        }
    .hanging div.csl-entry {
      margin-left:2em;
      text-indent:-2em;
    }
    div.csl-left-margin {
      min-width:2em;
      float:left;
    }
    div.csl-right-inline {
      margin-left:2em;
      padding-left:1em;
    }
    div.csl-indent {
      margin-left: 2em;
    }
  </style>
<link rel="stylesheet" href="include/psyteachr.css">
<link rel="stylesheet" href="include/webex.css">
<link rel="stylesheet" href="include/style.css">
</head>
<body data-spy="scroll" data-target="#toc">

<div class="container-fluid">
<div class="row">
  <header class="col-sm-12 col-lg-3 sidebar sidebar-book"><a class="sr-only sr-only-focusable" href="#content">Skip to main content</a>

    <div class="d-flex align-items-start justify-content-between">
      <h1>
        <a href="index.html" title="">Data visualisation using R, for researchers who don’t use R</a>
      </h1>
      <button class="btn btn-outline-primary d-lg-none ml-2 mt-1" type="button" data-toggle="collapse" data-target="#main-nav" aria-expanded="true" aria-controls="main-nav"><i class="fas fa-bars"></i><span class="sr-only">Show table of contents</span></button>
    </div>

    <div id="main-nav" class="collapse-lg">
      <form role="search">
        <input id="search" class="form-control" type="search" placeholder="Search" aria-label="Search">
</form>

      <nav aria-label="Table of contents"><h2>Table of contents</h2>
        <ul class="book-toc list-unstyled">
<li><a class="" href="index.html">Overview</a></li>
<li><a class="" href="introduction.html"><span class="header-section-number">1</span> Introduction</a></li>
<li><a class="active" href="getting-started.html"><span class="header-section-number">2</span> Getting Started</a></li>
<li><a class="" href="transforming-data.html"><span class="header-section-number">3</span> Transforming Data</a></li>
<li><a class="" href="representing-summary-statistics.html"><span class="header-section-number">4</span> Representing Summary Statistics</a></li>
<li><a class="" href="multi-part-plots.html"><span class="header-section-number">5</span> Multi-part Plots</a></li>
<li><a class="" href="advanced-plots.html"><span class="header-section-number">6</span> Advanced Plots</a></li>
<li><a class="" href="conclusion.html"><span class="header-section-number">7</span> Conclusion</a></li>
<li class="book-part">Appendices</li>
<li><a class="" href="additional-resources.html"><span class="header-section-number">A</span> Additional resources</a></li>
<li><a class="" href="additional-customisation-options.html"><span class="header-section-number">B</span> Additional customisation options</a></li>
<li><a class="" href="plotstyle.html"><span class="header-section-number">C</span> Styling Plots</a></li>
<li><a class="" href="advanced-plots-1.html"><span class="header-section-number">D</span> Advanced Plots</a></li>
<li><a class="" href="license.html">License</a></li>
<li><a class="" href="references.html">References</a></li>
</ul>

        <div class="book-extra">
          <p><a id="book-repo" href="https://github.com/psyteachr/introdataviz">View book source <i class="fab fa-github"></i></a></p>
        </div>
      </nav>
</div>
  </header><main class="col-sm-12 col-md-9 col-lg-7" id="content"><div id="getting-started" class="section level1" number="2">
<h1>
<span class="header-section-number">2</span> Getting Started<a class="anchor" aria-label="anchor" href="#getting-started"><i class="fas fa-link"></i></a>
</h1>
<div id="loading-packages" class="section level2" number="2.1">
<h2>
<span class="header-section-number">2.1</span> Loading packages<a class="anchor" aria-label="anchor" href="#loading-packages"><i class="fas fa-link"></i></a>
</h2>
<p>To load the packages that have the functions we need, use the <code><a href="https://rdrr.io/r/base/library.html">library()</a></code> function. Whilst you only need to install packages once, you need to load any packages you want to use with <code><a href="https://rdrr.io/r/base/library.html">library()</a></code> every time you start R or start a new session. When you load the <code>tidyverse</code>, you actually load several separate packages that are all part of the same collection and have been designed to work together. R will produce a message that tells you the names of the packages that have been loaded.</p>
<div class="sourceCode" id="cb2"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="kw"><a href="https://rdrr.io/r/base/library.html">library</a></span><span class="op">(</span><span class="va"><a href="https://tidyverse.tidyverse.org">tidyverse</a></span><span class="op">)</span>
<span class="kw"><a href="https://rdrr.io/r/base/library.html">library</a></span><span class="op">(</span><span class="va"><a href="https://patchwork.data-imaginist.com">patchwork</a></span><span class="op">)</span></code></pre></div>
</div>
<div id="loading-data" class="section level2" number="2.2">
<h2>
<span class="header-section-number">2.2</span> Loading data<a class="anchor" aria-label="anchor" href="#loading-data"><i class="fas fa-link"></i></a>
</h2>
<p>To load the <a href="https://osf.io/bj83f/files/" target="_blank">simulated data</a> we use the function <code><a href="https://readr.tidyverse.org/reference/read_delim.html">read_csv()</a></code> from the <code>readr</code> tidyverse package. Note that there are many other ways of reading data into R, but the benefit of this function is that it enters the data into the R environment in such a way that it makes most sense for other tidyverse packages.</p>
<div class="sourceCode" id="cb3"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="va">dat</span> <span class="op">&lt;-</span> <span class="fu"><a href="https://readr.tidyverse.org/reference/read_delim.html">read_csv</a></span><span class="op">(</span>file <span class="op">=</span> <span class="st">"ldt_data.csv"</span><span class="op">)</span></code></pre></div>
<p>This code has created an object <code>dat</code> into which you have read the data from the file <code>ldt_data.csv</code>. This object will appear in the environment pane in the top right. Note that the name of the data file must be in quotation marks and the file extension (<code>.csv</code>) must also be included. If you receive the error <code>…does not exist in current working directory</code> it is highly likely that you have made a typo in the file name (remember R is case sensitive), have forgotten to include the file extension <code>.csv</code>, or that the data file you want to load is not stored in your project folder. If you get the error <code>could not find function</code> it means you have either not loaded the correct package (a common beginner error is to write the code, but not run it), or you have made a typo in the function name.</p>
<p>You should always check after importing data that the resulting table looks like you expect. To view the dataset, click <code>dat</code> in the environment pane or run <code>View(dat)</code> in the console. The environment pane also tells us that the object <code>dat</code> has 100 observations of 7 variables, and this is a useful quick check to ensure one has loaded the right data. Note that the 7 variables have an additional piece of information <code>chr</code> and <code>num</code>; this specifies the kind of data in the column. Similar to Excel and SPSS, R uses this information (or variable type) to specify allowable manipulations of data. For instance character data such as the <code>id</code> cannot be averaged, while it is possible to do this with numerical data such as the <code>age</code>.</p>
</div>
<div id="handling-numeric-factors" class="section level2" number="2.3">
<h2>
<span class="header-section-number">2.3</span> Handling numeric factors<a class="anchor" aria-label="anchor" href="#handling-numeric-factors"><i class="fas fa-link"></i></a>
</h2>
<p>Another useful check is to use the functions <code><a href="https://rdrr.io/r/base/summary.html">summary()</a></code> and <code><a href="https://rdrr.io/r/utils/str.html">str()</a></code> (structure) to check what kind of data R thinks is in each column. Run the below code and look at the output of each, comparing it with what you know about the simulated dataset:</p>
<div class="sourceCode" id="cb4"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://rdrr.io/r/base/summary.html">summary</a></span><span class="op">(</span><span class="va">dat</span><span class="op">)</span>
<span class="fu"><a href="https://rdrr.io/r/utils/str.html">str</a></span><span class="op">(</span><span class="va">dat</span><span class="op">)</span></code></pre></div>
<p>Because the factor <code>language</code> is coded as 1 and 2, R has categorised this column as containing numeric information and unless we correct it, this will cause problems for visualisation and analysis. The code below shows how to recode numeric codes into labels.</p>
<ul>
<li>
<code><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> makes new columns in a data table, or overwrites a column;</li>
<li>
<code><a href="https://rdrr.io/r/base/factor.html">factor()</a></code> translates the language column into a factor with the labels "monolingual" and "bilingual". You can also use <code><a href="https://rdrr.io/r/base/factor.html">factor()</a></code> to set the display order of a column that contains words. Otherwise, they will display in alphabetical order. In this case we are replacing the numeric data (1 and 2) in the <code>language</code> column with the equivalent English labels <code>monolingual</code> for 1 and <code>bilingual</code> for 2. At the same time we will change the column type to be a factor, which is how R defines categorical data.</li>
</ul>
<div class="sourceCode" id="cb5"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="va">dat</span> <span class="op">&lt;-</span> <span class="fu"><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate</a></span><span class="op">(</span><span class="va">dat</span>, language <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/factor.html">factor</a></span><span class="op">(</span>
  x <span class="op">=</span> <span class="va">language</span>, <span class="co"># column to translate</span>
  levels <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="fl">1</span>, <span class="fl">2</span><span class="op">)</span>, <span class="co"># values of the original data in preferred order</span>
  labels <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="st">"monolingual"</span>, <span class="st">"bilingual"</span><span class="op">)</span> <span class="co"># labels for display</span>
<span class="op">)</span><span class="op">)</span></code></pre></div>
<p>Make sure that you always check the output of any code that you run. If after running this code <code>language</code> is full of <code>NA</code> values, it means that you have run the code twice. The first time would have worked and transformed the values from <code>1</code> to <code>monolingual</code> and <code>2</code> to <code>bilingual</code>. If you run the code again on the same dataset, it will look for the values <code>1</code> and <code>2</code>, and because there are no longer any that match, it will return NA. If this happens, you will need to reload the dataset from the csv file.</p>
<p>A good way to avoid this is never to overwrite data, but to always store the output of code in new objects (e.g., <code>dat_recoded</code>) or new variables (<code>language_recoded</code>). For the purposes of this tutorial, overwriting provides a useful teachable moment so we'll leave it as it is.</p>
</div>
<div id="argument-names" class="section level2" number="2.4">
<h2>
<span class="header-section-number">2.4</span> Argument names<a class="anchor" aria-label="anchor" href="#argument-names"><i class="fas fa-link"></i></a>
</h2>
<p>Each function has a list of arguments it can take, and a default order for those arguments. You can get more information on each function by entering <code>?function_name</code> into the console, although be aware that learning to read the help documentation in R is a skill in itself. When you are writing R code, as long as you stick to the default order, you do not have to explicitly call the argument names, for example, the above code could also be written as:</p>
<div class="sourceCode" id="cb6"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="va">dat</span> <span class="op">&lt;-</span> <span class="fu"><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate</a></span><span class="op">(</span><span class="va">dat</span>, language <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/factor.html">factor</a></span><span class="op">(</span>
  <span class="va">language</span>,
  <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="fl">1</span>, <span class="fl">2</span><span class="op">)</span>,
  <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="st">"monolingual"</span>, <span class="st">"bilingual"</span><span class="op">)</span>
<span class="op">)</span><span class="op">)</span></code></pre></div>
<p>One of the challenges in learning R is that many of the "helpful" examples and solutions you will find online do not include argument names and so for novice learners are completely opaque. In this tutorial, we will include the argument names the first time a function is used, however, we will remove some argument names from subsequent examples to facilitate knowledge transfer to the help available online.</p>
</div>
<div id="summarising-data" class="section level2" number="2.5">
<h2>
<span class="header-section-number">2.5</span> Summarising data<a class="anchor" aria-label="anchor" href="#summarising-data"><i class="fas fa-link"></i></a>
</h2>
<p>You can calculate and plot some basic descriptive information about the demographics of our sample using the imported dataset without any additional wrangling (i.e., data processing). The code below uses the <code>%&gt;%</code> operator, otherwise known as the <em>pipe,</em> and can be translated as "<em>and then"</em>. For example, the below code can be read as:</p>
<ul>
<li><p>Start with the dataset <code>dat</code> <em>and then;</em></p></li>
<li><p>Group it by the variable <code>language</code> <em>and then;</em></p></li>
<li><p>Count the number of observations in each group <em>and then;</em></p></li>
<li><p>Remove the grouping</p></li>
</ul>
<div class="sourceCode" id="cb7"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="va">dat</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/group_by.html">group_by</a></span><span class="op">(</span><span class="va">language</span><span class="op">)</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/count.html">count</a></span><span class="op">(</span><span class="op">)</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/group_by.html">ungroup</a></span><span class="op">(</span><span class="op">)</span></code></pre></div>
<div class="inline-table"><table class="table table-sm">
<thead><tr>
<th style="text-align:center;">
language
</th>
<th style="text-align:center;">
n
</th>
</tr></thead>
<tbody>
<tr>
<td style="text-align:center;">
monolingual
</td>
<td style="text-align:center;">
55
</td>
</tr>
<tr>
<td style="text-align:center;">
bilingual
</td>
<td style="text-align:center;">
45
</td>
</tr>
</tbody>
</table></div>
<p><code><a href="https://dplyr.tidyverse.org/reference/group_by.html">group_by()</a></code> does not result in surface level changes to the dataset, rather, it changes the underlying structure so that if groups are specified, whatever functions called next are performed separately on each level of the grouping variable. This grouping remains in the object that is created so it is important to remove it with <code><a href="https://dplyr.tidyverse.org/reference/group_by.html">ungroup()</a></code> to avoid future operations on the object unknowingly being performed by groups.</p>
<p>The above code therefore counts the number of observations in each group of the variable <code>language</code>. If you just need the total number of observations, you could remove the <code><a href="https://dplyr.tidyverse.org/reference/group_by.html">group_by()</a></code> and <code><a href="https://dplyr.tidyverse.org/reference/group_by.html">ungroup()</a></code> lines, which would perform the operation on the whole dataset, rather than by groups:</p>
<div class="sourceCode" id="cb8"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="va">dat</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/count.html">count</a></span><span class="op">(</span><span class="op">)</span></code></pre></div>
<div class="inline-table"><table class="table table-sm">
<thead><tr>
<th style="text-align:center;">
n
</th>
</tr></thead>
<tbody><tr>
<td style="text-align:center;">
100
</td>
</tr></tbody>
</table></div>
<p>Similarly, we may wish to calculate the mean age (and SD) of the sample and we can do so using the function <code><a href="https://dplyr.tidyverse.org/reference/summarise.html">summarise()</a></code> from the <code>dplyr</code> tidyverse package.</p>
<div class="sourceCode" id="cb9"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="va">dat</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/summarise.html">summarise</a></span><span class="op">(</span>mean_age <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/mean.html">mean</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span>,
            sd_age <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/stats/sd.html">sd</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span>,
            n_values <span class="op">=</span> <span class="fu"><a href="https://dplyr.tidyverse.org/reference/context.html">n</a></span><span class="op">(</span><span class="op">)</span><span class="op">)</span></code></pre></div>
<div class="inline-table"><table class="table table-sm">
<thead><tr>
<th style="text-align:center;">
mean_age
</th>
<th style="text-align:center;">
sd_age
</th>
<th style="text-align:center;">
n_values
</th>
</tr></thead>
<tbody><tr>
<td style="text-align:center;">
29.75
</td>
<td style="text-align:center;">
8.28
</td>
<td style="text-align:center;">
100
</td>
</tr></tbody>
</table></div>
<p>This code produces summary data in the form of a column named <code>mean_age</code> that contains the result of calculating the mean of the variable <code>age</code>. It then creates <code>sd_age</code> which does the same but for standard deviation. Finally, it uses the function <code><a href="https://dplyr.tidyverse.org/reference/context.html">n()</a></code> to add the number of values used to calculate the statistic in a column named <code>n_values</code> - this is a useful sanity check whenever you make summary statistics.</p>
<p>Note that the above code will not save the result of this operation, it will simply output the result in the console. If you wish to save it for future use, you can store it in an object by using the <code>&lt;-</code> notation and print it later by typing the object name.</p>
<div class="sourceCode" id="cb10"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="va">age_stats</span> <span class="op">&lt;-</span> <span class="va">dat</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/summarise.html">summarise</a></span><span class="op">(</span>mean_age <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/mean.html">mean</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span>,
            sd_age <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/stats/sd.html">sd</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span>,
            n_values <span class="op">=</span> <span class="fu"><a href="https://dplyr.tidyverse.org/reference/context.html">n</a></span><span class="op">(</span><span class="op">)</span><span class="op">)</span></code></pre></div>
<p>Finally, the <code><a href="https://dplyr.tidyverse.org/reference/group_by.html">group_by()</a></code> function will work in the same way when calculating summary statistics -- the output of the function that is called after <code><a href="https://dplyr.tidyverse.org/reference/group_by.html">group_by()</a></code> will be produced for each level of the grouping variable.</p>
<div class="sourceCode" id="cb11"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="va">dat</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/group_by.html">group_by</a></span><span class="op">(</span><span class="va">language</span><span class="op">)</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/summarise.html">summarise</a></span><span class="op">(</span>mean_age <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/mean.html">mean</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span>,
            sd_age <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/stats/sd.html">sd</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span>,
            n_values <span class="op">=</span> <span class="fu"><a href="https://dplyr.tidyverse.org/reference/context.html">n</a></span><span class="op">(</span><span class="op">)</span><span class="op">)</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/group_by.html">ungroup</a></span><span class="op">(</span><span class="op">)</span></code></pre></div>
<div class="inline-table"><table class="table table-sm">
<thead><tr>
<th style="text-align:center;">
language
</th>
<th style="text-align:center;">
mean_age
</th>
<th style="text-align:center;">
sd_age
</th>
<th style="text-align:center;">
n_values
</th>
</tr></thead>
<tbody>
<tr>
<td style="text-align:center;">
monolingual
</td>
<td style="text-align:center;">
27.96
</td>
<td style="text-align:center;">
6.78
</td>
<td style="text-align:center;">
55
</td>
</tr>
<tr>
<td style="text-align:center;">
bilingual
</td>
<td style="text-align:center;">
31.93
</td>
<td style="text-align:center;">
9.44
</td>
<td style="text-align:center;">
45
</td>
</tr>
</tbody>
</table></div>
</div>
<div id="bar-chart-of-counts" class="section level2" number="2.6">
<h2>
<span class="header-section-number">2.6</span> Bar chart of counts<a class="anchor" aria-label="anchor" href="#bar-chart-of-counts"><i class="fas fa-link"></i></a>
</h2>
<p>For our first plot, we will make a simple bar chart of counts that shows the number of participants in each <code>language</code> group.</p>
<div class="sourceCode" id="cb12"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span>data <span class="op">=</span> <span class="va">dat</span>, mapping <span class="op">=</span> <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span>x <span class="op">=</span> <span class="va">language</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar</a></span><span class="op">(</span><span class="op">)</span></code></pre></div>
<div class="figure" style="text-align: center">
<span style="display:block;" id="fig:bar1"></span>
<img src="02-ch2_files/figure-html/bar1-1.png" alt="Bar chart of counts." width="80%"><p class="caption">
Figure 2.1: Bar chart of counts.
</p>
</div>
<div class="sourceCode" id="cb13"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span>data <span class="op">=</span> <span class="va">dat</span>, mapping <span class="op">=</span> <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span>x <span class="op">=</span> <span class="va">language</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span> 
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar</a></span><span class="op">(</span><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span>y <span class="op">=</span> <span class="op">(</span><span class="va">..count..</span><span class="op">)</span><span class="op">/</span><span class="fu"><a href="https://rdrr.io/r/base/sum.html">sum</a></span><span class="op">(</span><span class="va">..count..</span><span class="op">)</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span> 
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/scale_continuous.html">scale_y_continuous</a></span><span class="op">(</span>name <span class="op">=</span> <span class="st">"Percent"</span>, labels<span class="op">=</span><span class="fu">scales</span><span class="fu">::</span><span class="va"><a href="https://scales.r-lib.org/reference/label_percent.html">percent</a></span><span class="op">)</span> </code></pre></div>
<div class="inline-figure"><img src="02-ch2_files/figure-html/unnamed-chunk-2-1.png" width="80%" style="display: block; margin: auto;"></div>
<p>The first line of code sets up the base of the plot.</p>
<ul>
<li><p><code>data</code> specifies which data source to use for the plot</p></li>
<li><p><code>mapping</code> specifies which variables to map to which aesthetics (<code>aes</code>) of the plot. Mappings describe how variables in the data are mapped to visual properties (aesthetics) of geoms.</p></li>
<li><p><code>x</code> specifies which variable to put on the x-axis</p></li>
</ul>
<p>The second line of code adds a <code>geom</code>, and is connected to the base code with <code>+</code>. In this case, we ask for <code><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar()</a></code>. Each <code>geom</code> has an associated default statistic. For <code><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar()</a></code>, the default statistic is to count the data passed to it. This means that you do not have to specify a <code>y</code> variable when making a bar plot of counts; when given an <code>x</code> variable <code><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar()</a></code> will automatically calculate counts of the groups in that variable. In this example, it counts the number of data points that are in each category of the <code>language</code> variable.</p>
<p>The base and geoms layers work in symbiosis so it is worthwhile checking the mapping rules as these are related to the default statistic for the plot's geom.</p>
</div>
<div id="aggregates-and-percentages" class="section level2" number="2.7">
<h2>
<span class="header-section-number">2.7</span> Aggregates and percentages<a class="anchor" aria-label="anchor" href="#aggregates-and-percentages"><i class="fas fa-link"></i></a>
</h2>
<p>If your dataset already has the counts that you want to plot, you can set <code>stat="identity"</code> inside of <code><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar()</a></code> to use that number instead of counting rows. For example, to plot percentages rather than counts within <code>ggplot2</code>, you can calculate these and store them in a new object that is then used as the dataset. You can do this in the software you are most comfortable in, save the new data, and import it as a new table, or you can use code to manipulate the data.</p>
<div class="sourceCode" id="cb14"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="va">dat_percent</span> <span class="op">&lt;-</span> <span class="va">dat</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>    <span class="co"># start with the data in dat</span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/count.html">count</a></span><span class="op">(</span><span class="va">language</span><span class="op">)</span> <span class="op"><a href="https://magrittr.tidyverse.org/reference/pipe.html">%&gt;%</a></span>     <span class="co"># count rows per language (makes a new column called n)</span>
  <span class="fu"><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate</a></span><span class="op">(</span>percent <span class="op">=</span> <span class="op">(</span><span class="va">n</span><span class="op">/</span><span class="fu"><a href="https://rdrr.io/r/base/sum.html">sum</a></span><span class="op">(</span><span class="va">n</span><span class="op">)</span><span class="op">*</span><span class="fl">100</span><span class="op">)</span><span class="op">)</span> <span class="co"># make a new column 'percent' equal to </span>
                                   <span class="co"># n divided by the sum of n times 100</span></code></pre></div>
<p>Notice that we are now omitting the names of the arguments <code>data</code> and <code>mapping</code> in the <code><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot()</a></code> function.</p>
<div class="sourceCode" id="cb15"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span><span class="va">dat_percent</span>, <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span>x <span class="op">=</span> <span class="va">language</span>, y <span class="op">=</span> <span class="va">percent</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar</a></span><span class="op">(</span>stat<span class="op">=</span><span class="st">"identity"</span><span class="op">)</span> </code></pre></div>
<div class="figure" style="text-align: center">
<span style="display:block;" id="fig:bar-precalc"></span>
<img src="02-ch2_files/figure-html/bar-precalc-1.png" alt="Bar chart of pre-calculated counts." width="80%"><p class="caption">
Figure 2.2: Bar chart of pre-calculated counts.
</p>
</div>
</div>
<div id="histogram" class="section level2" number="2.8">
<h2>
<span class="header-section-number">2.8</span> Histogram<a class="anchor" aria-label="anchor" href="#histogram"><i class="fas fa-link"></i></a>
</h2>
<p>The code to plot a histogram of <code>age</code> is very similar to the bar chart code. We start by setting up the plot space, the dataset to use, and mapping the variables to the relevant axis. In this case, we want to plot a histogram with <code>age</code> on the x-axis:</p>
<div class="sourceCode" id="cb16"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span><span class="va">dat</span>, <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span>x <span class="op">=</span> <span class="va">age</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram</a></span><span class="op">(</span><span class="op">)</span></code></pre></div>
<div class="figure" style="text-align: center">
<span style="display:block;" id="fig:histogram1"></span>
<img src="02-ch2_files/figure-html/histogram1-1.png" alt="Histogram of ages." width="80%"><p class="caption">
Figure 2.3: Histogram of ages.
</p>
</div>
<p>The base statistic for <code><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram()</a></code> is also count, and by default <code><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram()</a></code> divides the x-axis into 30 "bins" and counts how many observations are in each bin and so the y-axis does not need to be specified. When you run the code to produce the histogram, you will get the message "stat_bin() using bins = 30. Pick better value with binwidth". You can change this by either setting the number of bins (e.g., <code>bins = 20</code>) or the width of each bin (e.g., <code>binwidth = 5</code>) as an argument.</p>
<div class="sourceCode" id="cb17"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span><span class="va">dat</span>, <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span>x <span class="op">=</span> <span class="va">age</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram</a></span><span class="op">(</span>binwidth <span class="op">=</span> <span class="fl">5</span><span class="op">)</span></code></pre></div>
<div class="figure" style="text-align: center">
<span style="display:block;" id="fig:histogram2"></span>
<img src="02-ch2_files/figure-html/histogram2-1.png" alt="Histogram of ages where each bin covers five years." width="80%"><p class="caption">
Figure 2.4: Histogram of ages where each bin covers five years.
</p>
</div>
</div>
<div id="customisation-1" class="section level2" number="2.9">
<h2>
<span class="header-section-number">2.9</span> Customisation 1<a class="anchor" aria-label="anchor" href="#customisation-1"><i class="fas fa-link"></i></a>
</h2>
<p>So far we have made basic plots with the default visual appearance. Before we move on to the experimental data, we will introduce some simple visual customisation options. There are many ways in which you can control or customise the visual appearance of figures in R. However, once you understand the logic of one, it becomes easier to understand others that you may see in other examples. The visual appearance of elements can be customised within a geom itself, within the aesthetic mapping, or by connecting additional layers with <code>+</code>. In this section we look at the simplest and most commonly-used customisations: changing colours, adding axis labels, and adding themes.</p>
<div id="changing-colours" class="section level3" number="2.9.1">
<h3>
<span class="header-section-number">2.9.1</span> Changing colours<a class="anchor" aria-label="anchor" href="#changing-colours"><i class="fas fa-link"></i></a>
</h3>
<p>For our basic bar chart, you can control colours used to display the bars by setting <code>fill</code> (internal colour) and <code>colour</code> (outline colour) inside the geom function. This method changes <strong>all</strong> bars; we will show you later how to set fill or colour separately for different groups.</p>
<div class="sourceCode" id="cb18"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span><span class="va">dat</span>, <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram</a></span><span class="op">(</span>binwidth <span class="op">=</span> <span class="fl">1</span>, 
                 fill <span class="op">=</span> <span class="st">"white"</span>, 
                 colour <span class="op">=</span> <span class="st">"black"</span><span class="op">)</span></code></pre></div>
<div class="figure" style="text-align: center">
<span style="display:block;" id="fig:histogram-fill-color"></span>
<img src="02-ch2_files/figure-html/histogram-fill-color-1.png" alt="Histogram with custom colors for bar fill and line colors." width="80%"><p class="caption">
Figure 2.5: Histogram with custom colors for bar fill and line colors.
</p>
</div>
</div>
<div id="editing-axis-names-and-labels" class="section level3" number="2.9.2">
<h3>
<span class="header-section-number">2.9.2</span> Editing axis names and labels<a class="anchor" aria-label="anchor" href="#editing-axis-names-and-labels"><i class="fas fa-link"></i></a>
</h3>
<p>To edit axis names and labels you can connect <code>scale_*</code> functions to your plot with <code>+</code> to add layers. These functions are part of <code>ggplot2</code> and the one you use depends on which aesthetic you wish to edit (e.g., x-axis, y-axis, fill, colour) as well as the type of data it represents (discrete, continuous).</p>
<p>For the bar chart of counts, the x-axis is mapped to a discrete (categorical) variable whilst the y-axis is continuous. For each of these there is a relevant scale function with various elements that can be customised. Each axis then has its own function added as a layer to the basic plot.</p>
<div class="sourceCode" id="cb19"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span><span class="va">dat</span>, <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span><span class="va">language</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar</a></span><span class="op">(</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/scale_discrete.html">scale_x_discrete</a></span><span class="op">(</span>name <span class="op">=</span> <span class="st">"Language group"</span>, 
                   labels <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="st">"Monolingual"</span>, <span class="st">"Bilingual"</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/scale_continuous.html">scale_y_continuous</a></span><span class="op">(</span>name <span class="op">=</span> <span class="st">"Number of participants"</span>,
                     breaks <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="fl">0</span>,<span class="fl">10</span>,<span class="fl">20</span>,<span class="fl">30</span>,<span class="fl">40</span>,<span class="fl">50</span><span class="op">)</span><span class="op">)</span></code></pre></div>
<div class="figure" style="text-align: center">
<span style="display:block;" id="fig:bar3"></span>
<img src="02-ch2_files/figure-html/bar3-1.png" alt="Bar chart with custom axis labels." width="80%"><p class="caption">
Figure 2.6: Bar chart with custom axis labels.
</p>
</div>
<ul>
<li><p><code>name</code> controls the overall name of the axis (note the use of quotation marks)</p></li>
<li><p><code>labels</code> controls the names of the conditions with a discrete variable.</p></li>
<li><p><code><a href="https://rdrr.io/r/base/c.html">c()</a></code> is a function that you will see in many different contexts and is used to combine multiple values. In this case, the labels we want to apply are combined within <code><a href="https://rdrr.io/r/base/c.html">c()</a></code> by enclosing each word within their own parenthesis, and are in the order displayed on the plot. A very common error is to forget to enclose multiple values in <code><a href="https://rdrr.io/r/base/c.html">c()</a></code>.</p></li>
<li><p><code>breaks</code> controls the tick marks on the axis. Again, because there are multiple values, they are enclosed within <code><a href="https://rdrr.io/r/base/c.html">c()</a></code>. Because they are numeric and not text, they do not need quotation marks.</p></li>
</ul>
<p>A common error is to map the wrong type of <code>scale_</code> function to a variable. Try running the below code:</p>
<div class="sourceCode" id="cb20"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="co"># produces an error</span>
<span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span><span class="va">dat</span>, <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span><span class="va">language</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar</a></span><span class="op">(</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/scale_continuous.html">scale_x_continuous</a></span><span class="op">(</span>name <span class="op">=</span> <span class="st">"Language group"</span>, 
                     labels <span class="op">=</span> <span class="fu"><a href="https://rdrr.io/r/base/c.html">c</a></span><span class="op">(</span><span class="st">"Monolingual"</span>, <span class="st">"Bilingual"</span><span class="op">)</span><span class="op">)</span> </code></pre></div>
<p>This will produce the error <code>Discrete value supplied to continuous scale</code> because we have used a <code>continuous</code> scale function, despite the fact that x-axis variable is discrete. If you get this error (or the reverse), check the type of data on each axis and the function you have used.</p>
</div>
<div id="adding-a-theme" class="section level3" number="2.9.3">
<h3>
<span class="header-section-number">2.9.3</span> Adding a theme<a class="anchor" aria-label="anchor" href="#adding-a-theme"><i class="fas fa-link"></i></a>
</h3>
<p><code>ggplot2</code> has a number of built-in visual themes that you can apply as an extra layer. The below code updates the x-axis and y-axis labels to the histogram, but also applies <code><a href="https://ggplot2.tidyverse.org/reference/ggtheme.html">theme_minimal()</a></code>. Each part of a theme can be independently customised, which may be necessary, for example, if you have journal guidelines on fonts for publication. There are further instructions for how to do this in the online appendices.</p>
<div class="sourceCode" id="cb21"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span><span class="va">dat</span>, <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram</a></span><span class="op">(</span>binwidth <span class="op">=</span> <span class="fl">1</span>, fill <span class="op">=</span> <span class="st">"wheat"</span>, color <span class="op">=</span> <span class="st">"black"</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/scale_continuous.html">scale_x_continuous</a></span><span class="op">(</span>name <span class="op">=</span> <span class="st">"Participant age (years)"</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggtheme.html">theme_minimal</a></span><span class="op">(</span><span class="op">)</span></code></pre></div>
<div class="figure" style="text-align: center">
<span style="display:block;" id="fig:histogram-theme"></span>
<img src="02-ch2_files/figure-html/histogram-theme-1.png" alt="Histogram with a custom theme." width="80%"><p class="caption">
Figure 2.7: Histogram with a custom theme.
</p>
</div>
<p>You can set the theme globally so that all subsequent plots use a theme. <code><a href="https://ggplot2.tidyverse.org/reference/theme_get.html">theme_set()</a></code> is not part of a <code><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot()</a></code> object, you should run this code on its own. It may be useful to add this code to the top of your script so that all plots produced subsequently use the same theme.</p>
<div class="sourceCode" id="cb22"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/theme_get.html">theme_set</a></span><span class="op">(</span><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggtheme.html">theme_minimal</a></span><span class="op">(</span><span class="op">)</span><span class="op">)</span></code></pre></div>
<p>If you wished to return to the default theme, change the above to specify <code><a href="https://ggplot2.tidyverse.org/reference/ggtheme.html">theme_grey()</a></code>.</p>
</div>
</div>
<div id="activities-1" class="section level2" number="2.10">
<h2>
<span class="header-section-number">2.10</span> Activities 1<a class="anchor" aria-label="anchor" href="#activities-1"><i class="fas fa-link"></i></a>
</h2>
<p>Before you move on try the following:</p>
<ol style="list-style-type: decimal">
<li>Add a layer that edits the <strong>name</strong> of the y-axis histogram label to <code>Number of participants</code>.</li>
</ol>
<div class="webex-solution">
<button>
Solution 1
</button>
<div class="sourceCode" id="cb23"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span><span class="va">dat</span>, <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram</a></span><span class="op">(</span>binwidth <span class="op">=</span> <span class="fl">1</span>, fill <span class="op">=</span> <span class="st">"wheat"</span>, color <span class="op">=</span> <span class="st">"black"</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/scale_continuous.html">scale_x_continuous</a></span><span class="op">(</span>name <span class="op">=</span> <span class="st">"Participant age (years)"</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggtheme.html">theme_minimal</a></span><span class="op">(</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/scale_continuous.html">scale_y_continuous</a></span><span class="op">(</span>name <span class="op">=</span> <span class="st">"Number of participants"</span><span class="op">)</span></code></pre></div>
</div>
<ol start="2" style="list-style-type: decimal">
<li>Change the colour of the bars in the bar chart to red.</li>
</ol>
<div class="webex-solution">
<button>
Solution 2
</button>
<div class="sourceCode" id="cb24"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span>data <span class="op">=</span> <span class="va">dat</span>, mapping <span class="op">=</span> <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span>x <span class="op">=</span> <span class="va">language</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_bar.html">geom_bar</a></span><span class="op">(</span>fill <span class="op">=</span> <span class="st">"red"</span><span class="op">)</span></code></pre></div>
</div>
<ol start="3" style="list-style-type: decimal">
<li>Remove <code><a href="https://ggplot2.tidyverse.org/reference/ggtheme.html">theme_minimal()</a></code> from the histogram and instead apply one of the other available themes. To find out about other available themes, start typing <code>theme_</code> and the auto-complete will show you the available options - this will only work if you have loaded the <code>tidyverse</code> library with <code><a href="https://tidyverse.tidyverse.org">library(tidyverse)</a></code>.</li>
</ol>
<div class="webex-solution">
<button>
Solution 3
</button>
<div class="sourceCode" id="cb25"><pre class="downlit sourceCode r">
<code class="sourceCode R"><span class="co">#multiple options here e.g., theme_classic()</span>
<span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span><span class="va">dat</span>, <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram</a></span><span class="op">(</span>binwidth <span class="op">=</span> <span class="fl">1</span>, fill <span class="op">=</span> <span class="st">"wheat"</span>, color <span class="op">=</span> <span class="st">"black"</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/scale_continuous.html">scale_x_continuous</a></span><span class="op">(</span>name <span class="op">=</span> <span class="st">"Participant age (years)"</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggtheme.html">theme_classic</a></span><span class="op">(</span><span class="op">)</span>

<span class="co"># theme_bw()</span>
<span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggplot.html">ggplot</a></span><span class="op">(</span><span class="va">dat</span>, <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/aes.html">aes</a></span><span class="op">(</span><span class="va">age</span><span class="op">)</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/geom_histogram.html">geom_histogram</a></span><span class="op">(</span>binwidth <span class="op">=</span> <span class="fl">1</span>, fill <span class="op">=</span> <span class="st">"wheat"</span>, color <span class="op">=</span> <span class="st">"black"</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/scale_continuous.html">scale_x_continuous</a></span><span class="op">(</span>name <span class="op">=</span> <span class="st">"Participant age (years)"</span><span class="op">)</span> <span class="op">+</span>
  <span class="fu"><a href="https://ggplot2.tidyverse.org/reference/ggtheme.html">theme_bw</a></span><span class="op">(</span><span class="op">)</span></code></pre></div>
</div>

</div>
</div>
<script>

/* update total correct if #webex-total_correct exists */
update_total_correct = function() {
  console.log("webex: update total_correct");

  if (t = document.getElementById("webex-total_correct")) {
    var correct = document.getElementsByClassName("webex-correct").length;
    var solvemes = document.getElementsByClassName("webex-solveme").length;
    var radiogroups = document.getElementsByClassName("webex-radiogroup").length;
    var selects = document.getElementsByClassName("webex-select").length;
    
    t.innerHTML = correct + " of " + (solvemes + radiogroups + selects) + " correct";
  }
}

/* webex-solution button toggling function */
b_func = function() {
  console.log("webex: toggle hide");
  
  var cl = this.parentElement.classList;
  if (cl.contains('open')) {
    cl.remove("open");
  } else {
    cl.add("open");
  }
}

/* function for checking solveme answers */
solveme_func = function(e) {
  console.log("webex: check solveme");

  var real_answers = JSON.parse(this.dataset.answer);
  var my_answer = this.value;
  var cl = this.classList;
  if (cl.contains("ignorecase")) {
    my_answer = my_answer.toLowerCase();
  }
  if (cl.contains("nospaces")) {
    my_answer = my_answer.replace(/ /g, "")
  }

  if (my_answer == "") {
    cl.remove("webex-correct");
    cl.remove("webex-incorrect");
  } else if (real_answers.includes(my_answer)) {
    cl.add("webex-correct");
    cl.remove("webex-incorrect");
  } else {
    cl.add("webex-incorrect");
    cl.remove("webex-correct");
  }

  // match numeric answers within a specified tolerance
  if(this.dataset.tol > 0){
    var tol = JSON.parse(this.dataset.tol);
    var matches = real_answers.map(x => Math.abs(x - my_answer) < tol)
    if (matches.reduce((a, b) => a + b, 0) > 0) {
      cl.add("webex-correct");
    } else {
      cl.remove("webex-correct");
    }
  }

  // added regex bit
  if (cl.contains("regex")){
    answer_regex = RegExp(real_answers.join("|"))
    if (answer_regex.test(my_answer)) {
      cl.add("webex-correct");
    }
  }

  update_total_correct();
}

/* function for checking select answers */
select_func = function(e) {
  console.log("webex: check select");
  
  var cl = this.classList
  
  /* add style */
  cl.remove("webex-incorrect");
  cl.remove("webex-correct");
  if (this.value == "answer") {
    cl.add("webex-correct");
  } else if (this.value != "blank") {
    cl.add("webex-incorrect");
  }
  
  update_total_correct();
}

/* function for checking radiogroups answers */
radiogroups_func = function(e) {
  console.log("webex: check radiogroups");

  var checked_button = document.querySelector('input[name=' + this.id + ']:checked');
  var cl = checked_button.parentElement.classList;
  var labels = checked_button.parentElement.parentElement.children;
  
  /* get rid of styles */
  for (i = 0; i < labels.length; i++) {
    labels[i].classList.remove("webex-incorrect");
    labels[i].classList.remove("webex-correct");
  }
  
  /* add style */
  if (checked_button.value == "answer") {
    cl.add("webex-correct");
  } else {
    cl.add("webex-incorrect");
  }
  
  update_total_correct();
}

window.onload = function() {
  console.log("onload");
  /* set up solution buttons */
  var buttons = document.getElementsByTagName("button");

  for (var i = 0; i < buttons.length; i++) {
    if (buttons[i].parentElement.classList.contains('webex-solution')) {
      buttons[i].onclick = b_func;
    }
  }

  /* set up webex-solveme inputs */
  var solveme = document.getElementsByClassName("webex-solveme");

  for (var i = 0; i < solveme.length; i++) {
    /* make sure input boxes don't auto-anything */
    solveme[i].setAttribute("autocomplete","off");
    solveme[i].setAttribute("autocorrect", "off");
    solveme[i].setAttribute("autocapitalize", "off");
    solveme[i].setAttribute("spellcheck", "false");
    solveme[i].value = "";

    /* adjust answer for ignorecase or nospaces */
    var cl = solveme[i].classList;
    var real_answer = solveme[i].dataset.answer;
    if (cl.contains("ignorecase")) {
      real_answer = real_answer.toLowerCase();
    }
    if (cl.contains("nospaces")) {
      real_answer = real_answer.replace(/ /g, "");
    }
    solveme[i].dataset.answer = real_answer;

    /* attach checking function */
    solveme[i].onkeyup = solveme_func;
    solveme[i].onchange = solveme_func;
  }
  
  /* set up radiogroups */
  var radiogroups = document.getElementsByClassName("webex-radiogroup");
  for (var i = 0; i < radiogroups.length; i++) {
    radiogroups[i].onchange = radiogroups_func;
  }
  
  /* set up selects */
  var selects = document.getElementsByClassName("webex-select");
  for (var i = 0; i < selects.length; i++) {
    selects[i].onchange = select_func;
  }

  update_total_correct();
}

</script><script>
$( document ).ready(function() {
  var cite = ' ';
  var psyteachr = ' <a href="https://psyteachr.github.io/"><img src="images/logos/psyteachr_logo.png" style="height: 31px; color: white;" alt="psyTeachR: Reproducible Research" /></a>';
  var license = ' <a rel="license" href="https://creativecommons.org/licenses/by-sa/4.0/" target="blank"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/88x31.png"></a>';

  $("footer div.row div:eq(1) p").html(
    psyteachr + license + cite
  );

  function move_sidebar() {
    var w = window.innerWidth;
    if (w < 992) {
      $("#toc").appendTo($("#main-nav"));
    } else {
      $("#toc").appendTo($("div.sidebar-chapter"));
    }
  }
  move_sidebar();
  window.onresize = move_sidebar;
});
</script><div class="chapter-nav">
<div class="prev"><a href="introduction.html"><span class="header-section-number">1</span> Introduction</a></div>
<div class="next"><a href="transforming-data.html"><span class="header-section-number">3</span> Transforming Data</a></div>
</div></main><div class="col-md-3 col-lg-2 d-none d-md-block sidebar sidebar-chapter">
    <nav id="toc" data-toggle="toc" aria-label="On this page"><h2>On this page</h2>
      <ul class="nav navbar-nav">
<li><a class="nav-link" href="#getting-started"><span class="header-section-number">2</span> Getting Started</a></li>
<li><a class="nav-link" href="#loading-packages"><span class="header-section-number">2.1</span> Loading packages</a></li>
<li><a class="nav-link" href="#loading-data"><span class="header-section-number">2.2</span> Loading data</a></li>
<li><a class="nav-link" href="#handling-numeric-factors"><span class="header-section-number">2.3</span> Handling numeric factors</a></li>
<li><a class="nav-link" href="#argument-names"><span class="header-section-number">2.4</span> Argument names</a></li>
<li><a class="nav-link" href="#summarising-data"><span class="header-section-number">2.5</span> Summarising data</a></li>
<li><a class="nav-link" href="#bar-chart-of-counts"><span class="header-section-number">2.6</span> Bar chart of counts</a></li>
<li><a class="nav-link" href="#aggregates-and-percentages"><span class="header-section-number">2.7</span> Aggregates and percentages</a></li>
<li><a class="nav-link" href="#histogram"><span class="header-section-number">2.8</span> Histogram</a></li>
<li>
<a class="nav-link" href="#customisation-1"><span class="header-section-number">2.9</span> Customisation 1</a><ul class="nav navbar-nav">
<li><a class="nav-link" href="#changing-colours"><span class="header-section-number">2.9.1</span> Changing colours</a></li>
<li><a class="nav-link" href="#editing-axis-names-and-labels"><span class="header-section-number">2.9.2</span> Editing axis names and labels</a></li>
<li><a class="nav-link" href="#adding-a-theme"><span class="header-section-number">2.9.3</span> Adding a theme</a></li>
</ul>
</li>
<li><a class="nav-link" href="#activities-1"><span class="header-section-number">2.10</span> Activities 1</a></li>
</ul>

      <div class="book-extra">
        <ul class="list-unstyled">
<li><a id="book-source" href="https://github.com/psyteachr/introdataviz/blob/master/book/02-ch2.Rmd">View source <i class="fab fa-github"></i></a></li>
          <li><a id="book-edit" href="https://github.com/psyteachr/introdataviz/edit/master/book/02-ch2.Rmd">Edit this page <i class="fab fa-github"></i></a></li>
        </ul>
</div>
    </nav>
</div>

</div>
</div> <!-- .container -->

<footer class="bg-primary text-light mt-5"><div class="container"><div class="row">

  <div class="col-12 col-md-6 mt-3">
    <p>"<strong>Data visualisation using R, for researchers who don’t use R</strong>" was written by Emily Nordmann, Phil McAleer, Wilhelmiina Toivo, Helena Paterson, Lisa DeBruine. It was last built on 2022-05-02.</p>
  </div>

  <div class="col-12 col-md-6 mt-3">
    <p>This book was built by the <a class="text-light" href="https://bookdown.org">bookdown</a> R package.</p>
  </div>

</div></div>
</footer>
</body>
</html>
